package com.zz.yt.lib.login.face;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.FaceDetector;

import com.blankj.utilcode.util.ImageUtils;
import com.whf.android.jar.util.log.LatteLogger;
import com.zz.yt.lib.login.R;
import com.zz.yt.lib.login.face.utils.FaceDetectorUtils;

import org.jetbrains.annotations.NotNull;

import java.io.File;

import io.fotoapparat.preview.Frame;

import static com.blankj.utilcode.util.ViewUtils.runOnUiThread;

import androidx.annotation.NonNull;


/**
 * 人脸识别
 *
 * @author qf
 * @version 1.0.4
 **/
public class FaceDistinguishPopup extends BaseFacePopup {

    @NonNull
    public static FaceDistinguishPopup create(Context context) {
        return new FaceDistinguishPopup(context);
    }

    private FaceDistinguishPopup(Context context) {
        super(context);
    }

    @Override
    protected int setLayout() {
         return R.layout.hai_popup_face_distinguish;
    }

    @Override
    protected void initViews() {
        initCameraView();
        //1.一直波纹当着
        //2.检查到人脸，环形进度加载。
        //3.调用接口，成功关闭界面。
    }

    @Override
    public void process(@NotNull Frame frame) {
        super.process(frame);
        if (isDetectingFace) {
            LatteLogger.i("显示摄像头");
            return;
        }
        isDetectingFace = true;
        FaceDetectorUtils.detectFace(frame, new FaceDetectorUtils.Callback() {
            @Override
            public void onFaceDetected(FaceDetector.Face[] faces, Bitmap bitmap) {
                final String imagePath = getImagePath();
                LatteLogger.i("检查到人脸：" + imagePath);
                //旋转图片
                bitmap = ImageUtils.rotate(bitmap, -frame.getRotation(), (frame.getSize().width >> 1), (frame.getSize().height >> 1));
                //保存图片
                ImageUtils.save(bitmap, imagePath, Bitmap.CompressFormat.JPEG);
                if (mClickFaceListener != null) {
                    runOnUiThread(() -> mClickFaceListener.onConfirm(imagePath));
                    close();
                }
            }

            @Override
            public void onFaceNotDetected() {
                isDetectingFace = false;
                LatteLogger.i("未检查到人脸");
                overtime();
            }
        });
    }

    @NonNull
    private String getImagePath() {
        final File dir = mContext.getExternalFilesDir(null);
        return (dir == null ? "" : (dir.getAbsolutePath() + "/")) + "face" + ".jpg";
    }

}
